/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package me.aviator.dao;

import java.io.Serializable;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;

/**
 *
 * @author Administrator
 */
public class CommonDao {
    private final Session session;
    public CommonDao(Session session){
        this.session=session;
    }
    
    public Serializable save(Object object) {
	return session.save(object);
    }
    
    public Object load(Class clazz, Serializable id) {
	return session.load(clazz, id);
    }
    
    public void delete(Object object){
        session.delete(object);
    }
    
    public void delete(Class clazz,Serializable id){
        session.delete(load(clazz, id));
    }
    
    public Integer deleteAll(final Class clazz){
        Query query=session.createQuery("delete"+clazz.getName());
        return new Integer(query.executeUpdate());
    }
    
    public Session getFactorySession(){
	return this.session;
    }
    
    public Object get(Class clazz, Serializable id) {
	return session.get(clazz, id);
    }
    
    public List find(final String queryString) {
	return session.createQuery(queryString).list();
    }
    
    /**
	 * @Enclosing_Method: find
	 * @Description: 获得某个类型的全部对象列表 
	 * @param clazz 对象Class
	 * @return
	 */
    public List find(final Class clazz) {
	return this.find("from " + clazz.getName());
    }

    
    /**
    * @Enclosing_Method: find
    * @Description: 根据约束条件获得某个对象的全部对象列表 
    * @param queryString 查询语句
    * @param criterions 约束条件
    * @return
    */
    public List find(final String queryString, final Criterion[] criterions) {	
	Criteria criteria = session.createCriteria(queryString);
	// 循环遍历添加约束条件
	for (int i = 0; i < criterions.length; i++) {
            criteria.add(criterions[i]);
	}
	return criteria.list();
    }
    
    /**
    * @Enclosing_Method: find
    * @Description: 根据约束条件获得某个对象的全部对象列表 
    * @param clazz 对象Class
    * @param criterions 约束条件
    * @return
    */
    public List find(final Class clazz, final Criterion[] criterions) {
	Criteria criteria = session.createCriteria(clazz);
	// 循环遍历添加约束条件
	for (int i = 0; i < criterions.length; i++) {
            criteria.add(criterions[i]);
	}
	return criteria.list();
    }
    
    /**
	 * @Enclosing_Method: find
	 * @Description: 根据约束条件获得某个对象的全部对象列表 
	 * @param clazz 对象Class
	 * @param criterions 约束条件
	 * @return
	 */
    public List find(final Class clazz, final Criterion criterion) {
	Criteria criteria = session.createCriteria(clazz);
	criteria.add(criterion);
	return criteria.list();
    }
    
    
}
